import router from '../../router/index';
import { Message } from 'element-ui';
import dynamicRouters from '../../router/dynamicRouters';
import { getUserRolePower } from '@/api/userRole.js';
import generateRouters from '../../utils/generateRouters';
import generateButtons from '../../utils/generateButtons';

const state = {
  routes: [], //权限路由
  buttons: [] //权限按钮
};

const mutations = {
  // 设置路由值
  setRoutes: (state, routes) => {
    state.routes = routes;
  },
  // 设置按钮权限值
  setButtons: (state, buttons) => {
    state.buttons = buttons;
  }
};

const actions = {
  async generateRoutes({ commit, state }) {
    // 获取用户路由权限
    let authorityData = await getUserRolePower({
      request_name: 'iot_maintenance' //此处值要改成自己应用的
    });
    if (authorityData.data && authorityData.data.length) {
      const userRouters = authorityData.data[0];
      // 根据权限树生成动态菜单路由
      const dynamicRouters = await generateRouters(userRouters);
      // 获取所有按钮权限
      const permissionButtons = await generateButtons(userRouters);
      return new Promise(resolve => {
        router.addRoutes(dynamicRouters);
        commit('setRoutes', dynamicRouters[0].children);
        commit('setButtons', permissionButtons);
        resolve();
      });
    } else {
      Message.error({
        message: '抱歉！您没有当前应用的权限，如有需要请联系管理员开通 ',
        duration: 0,
        showClose: true
      });
      throw Error('抱歉！您没有当前应用的权限，如有需要请联系管理员开通');
    }

    // return new Promise(resolve => {
    //   router.addRoutes(dynamicRouters);
    //   commit('setRoutes', dynamicRouters);
    //   resolve();
    // });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
